#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>
#include <QLabel>
#include <QProgressBar>
#include <QPushButton>
#include <QVBoxLayout>
#include <QLineEdit>
#include <QScrollArea>
#include <QMessageBox>
#include "userlabel.h"

#include "funddata.h"
#include "uifundlist.h"
#include "uifunddetail.h"



typedef struct{
    QListWidgetItem *item;
    UserLabel *dataLabel;
    FundData *fundData;
    QString code;
    UIFundDetail *detail;
}uiListData;

enum Except{ EXCEP_ZERO,EXCEP_ONE};

static UIFundList *uiFundList;
static QList<uiListData> uiList;

void MainWindow::updateList() {
    for(int i = 0; i < uiFundList->size(); i++) {
        addSingleFundLine(uiFundList->getCode(i), uiFundList->getCode(i));
    }
}

void MainWindow::fundShowDetail() {
    foreach(uiListData data, uiList) {
        if(data.code.compare(sender()->objectName()) == 0) {
            data.detail->show();
            break;
        }
    }
}

void MainWindow::addSingleFundLine(QString code, QString viewString) {
    uiListData newListData;
    // Data part
    newListData.detail = new UIFundDetail(code);
    newListData.detail->setWindowTitle(code);
    QObject::connect(newListData.detail, \
                     SIGNAL(updateViewString(QString, QString, float)), \
                     this, \
                     SLOT(updateViewString(QString, QString, float)));
    // UI part
    newListData.item = new QListWidgetItem();
    QWidget *widget = new QWidget();
    QHBoxLayout *layout = new QHBoxLayout();
    newListData.dataLabel = new UserLabel();
    newListData.dataLabel->setText(viewString);
    newListData.dataLabel->setObjectName(code);
    QObject::connect(newListData.dataLabel, SIGNAL(clicked()), this, SLOT(fundShowDetail()));
    layout->setContentsMargins(0, 0, 0, 0);
    layout->addWidget(newListData.dataLabel);

    widget->setLayout(layout);

    ui->fundListWidget->insertItem(ui->fundListWidget->count(), newListData.item);
    ui->fundListWidget->setItemWidget(newListData.item, widget);

    newListData.code = code;
    uiList.append(newListData);
}

void MainWindow::deleteSingleFundLine(QString code) {
    for(int i = 0; i < uiList.size(); i++) {
        if(uiList.at(i).code.compare(code) == 0) {
//            delete uiList.at(i).detail;
            uiList.at(i).detail->close();
            uiList.at(i).detail->deleteLater();
            // Delete ui
            QWidget *widget = ui->fundListWidget->itemWidget(uiList.at(i).item);
            QHBoxLayout *layout = (QHBoxLayout *)widget->layout();
            QLayoutItem *litem = nullptr;
            while((litem = layout->itemAt(0)) != nullptr) {
                layout->removeItem(litem);
                delete litem->widget();
                delete litem;
            }
            delete layout;
            delete widget;
            ui->fundListWidget->removeItemWidget(uiList.at(i).item);
            delete uiList.at(i).item;

            uiList.removeAt(i);
            break;
        }
    }
}

void MainWindow::receiveDeleteFund(QString code) {
    deleteSingleFundLine(code);
}

void MainWindow::receiveAddFund(QString code, QString viewString) {
    addSingleFundLine(code, viewString);
}

void MainWindow::updateViewString(QString code, QString viewString, float estimatedPersent) {
//    qDebug() << __func__;
    for(int i = 0; i < uiList.size(); i++) {
        if(uiList.at(i).code.compare(code) == 0) {
            uiList.at(i).dataLabel->setText(viewString);
            if(estimatedPersent >= 0.0) {
                uiList.at(i).dataLabel->setStyleSheet("color:red;");
            } else {
                uiList.at(i).dataLabel->setStyleSheet("color:green;");
            }
//            qDebug() << "newListData.dataLabel: " << uiList.at(i).dataLabel->width();
            break;
        }
    }
}



#include "sqlcipher.h"

void sqlTest() {
    SQLCipher *sql = new SQLCipher();
    qDebug() << "connect rslt: " << sql->open("000001");
    qDebug() << "set key rslt: " << sql->setKey("xiaowang");
    qDebug() << "exec rslt: " << sql->exec("PRAGMA cipher_compatibility = 3;");
    qDebug() << "exec rslt: " << sql->exec("select all_accumulated_net from fund_data;");
//    qDebug() << sql->getData();
}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
//    qDebug() << "app path" + qApp->applicationDirPath();
//    // Load sqlcipher
//    QPluginLoader driverload(qApp->applicationDirPath()+"plugins/sqldrivers/sqlitecipher.dll");
//    if(driverload.load()) {
//        qDebug() << "Load sqlcipher success";
//    } else {
//        qDebug() << "Load sqlcipher failed";
//    }

    timer = new QTimer();
    timer->setTimerType(Qt::VeryCoarseTimer);
    QObject::connect(timer, SIGNAL(timeout()), this, SLOT(timeroutHandle()));

    uiFundList = new UIFundList();

    QObject::connect(uiFundList, SIGNAL(deleteFund(QString)), this, SLOT(receiveDeleteFund(QString)));
    QObject::connect(uiFundList, SIGNAL(addFund(QString, QString)), this, SLOT(receiveAddFund(QString, QString)));

    qDebug() << "timer " << timer->isActive();
    timer->setInterval(2 * 60000);
//    timer->setInterval(1000);
    timer->start();
    qDebug() << "timer " << timer->isActive();
    updateList();

    relocate();

//    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLCIPHER");
//    qDebug() << QSqlDatabase::drivers();

//    sqlTest();
//
//    dl->ask(QUrl("https://gitee.com/Hemingway2003/christopher_fund_data/raw/master/fund/000001/000001"), "test");
}

MainWindow::~MainWindow()
{
    qDebug() << "exit" << endl;
    delete timer;
    uiFundList->close();
    // TODO: Delete uiDetail list
    for(int i = 0; i < uiList.size(); i++) {
        deleteSingleFundLine(uiList.at(i).code);
    }
    delete uiFundList;
    delete ui;
}

void MainWindow::relocate() {
    ui->fundListWidget->setGeometry(geometry().x() + 10, geometry().y(), width() - 20, height() - 30);
}

void MainWindow::resize() {
    int uiWidth = width();
    int uiHeight = height();
    int listWidth, listHeight;
    listWidth = uiWidth - 20;
    listHeight = uiHeight - 30;
    ui->fundListWidget->resize(listWidth, listHeight);
}

void MainWindow::timeroutHandle() {
//    qDebug() << "timeroutHandle" << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss:zzz") << " " << uiList.size();
    foreach(uiListData data, uiList) {
//        qDebug() << data.code;
        data.detail->askUpdateViewString();
    }

}

void MainWindow::on_actionExit_triggered() {
    qDebug() << "on_actionExit_triggered";
    QApplication::quit();
}

void MainWindow::closeEvent(QCloseEvent *event) {
    qDebug() << "closeEvent";
    QApplication::quit();
}

void MainWindow::on_actionAddStockCode_triggered() {
    // Stock part
    qDebug() << "on_actionAddStockCode_triggered" << endl;
}

void MainWindow::on_actionAddFundCode_triggered()
{
    // Fund part
    uiFundList->show();
}

void MainWindow::on_actionHideAll_triggered()
{
    foreach(uiListData data, uiList) {
        data.detail->close();
    }
}

void MainWindow::resizeEvent(QResizeEvent *event) {
    resize();
}
